package com.blb.http;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * HTTP文件下载
 */
public class HttpDownloadDemo {

    public static final String DIR = "D:\\download\\";

    /**
     * 文件下载
     * @param urlStr 网络地址
     * @param filename 文件名
     */
    public void download(String urlStr,String filename){
        try {
            //创建URL对象
            URL url = new URL(urlStr);
            //获得网络连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时
            conn.setConnectTimeout(5000);
            // 判断响应码
            if(conn.getResponseCode() == 200) {
                File dir = new File(DIR);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                try (
                        //获得输入流
                        InputStream inputStream = conn.getInputStream();
                        //创建输出流
                        OutputStream outputStream = new FileOutputStream(DIR + filename);
                ) {
                    //读取网络流，写入到本地文件
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(buf)) != -1) {
                        outputStream.write(buf, 0, len);
                    }
                    System.out.println("下载完成");
                    Runtime.getRuntime().exec("mspaint " + DIR + filename);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new HttpDownloadDemo().download("https://t7.baidu.com/it/u=1951548898,3927145&fm=193&f=GIF","dog.jpg");
    }
}
